package csu.web.credit_bank.controller;

import csu.web.credit_bank.pojo.dto.McqQuestionDto;
import csu.web.credit_bank.service.QuizService;
import csu.web.credit_bank.utils.JwtHelper;
import csu.web.credit_bank.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/quiz")
public class QuizController {

    @Autowired
    private QuizService quizService;

    @Autowired
    private JwtHelper jwtHelper;

    @GetMapping("/mcq")
    public Result<McqQuestionDto> getQuestion(@RequestHeader("Authorization") String authorizationHeader) {
        String token = jwtHelper.getTokenFromHeader(authorizationHeader);
        String userId = jwtHelper.getUserId(token);
        if (userId == null) {
            return Result.failure("用户未认证");
        }
        return quizService.getMcqQuestion(userId);
    }
    @PostMapping("/mcq/submit")
    public Result<Void> submitAnswer(@RequestBody Map<String, String> payload,
                                     @RequestHeader("Authorization") String authorizationHeader) {
        String token = jwtHelper.getTokenFromHeader(authorizationHeader);
        if (token == null) {
            return Result.failure("Authorization token is missing or invalid.");
        }
        String userId = jwtHelper.getUserId(token);
        if (userId == null) {
            return Result.failure("Invalid token: user not found.");
        }
        String questionId = payload.get("questionId");
        String userAnswer = payload.get("userAnswer");

        return quizService.checkMcqAnswer(userId, questionId, userAnswer);
    }
}